<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card>
            <!-- 警告区域 -->
            <el-alert
                title="注意：只允许为第三级分类设置相关参数！"
                type="warning"
                show-icon :closable="false">
            </el-alert>
            <!-- 选择商品分类区域 -->
            <el-row class="row">
                <el-col>
                    <span>选择商品分类：</span>
                    <el-cascader v-model="selectedCate" :options="cateList"
                        :props="cateProps" @change="cateChange" clearable>
                    </el-cascader>
                </el-col>
            </el-row>
            <!-- tab页签区域 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <!-- 动态参数 -->
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" :disabled="isButtonDisabled" size="mini" @click="addTitledialogVisible=true">添加参数</el-button>
                <el-table :data="manyTableData" border stripe>
                    <el-table-column type="expand">
                      <!-- 循环显示参数 -->
                      <template slot-scope="scope">
                        <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
                        <!-- 输入新参数 -->
                        <el-input
                          class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                        </el-input>
                        <!--New Tag  -->
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                      </template>
                    </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <!-- 静态属性 -->
            <el-tab-pane label="静态属性" name="only">
                <el-button type="primary" :disabled="isButtonDisabled" size="mini" @click="addTitledialogVisible=true">添加属性</el-button>
                 <el-table :data="onlyTableData" border stripe>
                    <el-table-column type="expand">
                      <!-- 循环显示参数 -->
                      <template slot-scope="scope">
                        <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
                        <!-- 输入新参数 -->
                        <el-input
                          class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                        </el-input>
                        <!--New Tag  -->
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                      </template>
                    </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
        </el-card>
        <!-- 添加对话框 -->
        <el-dialog :title="'添加'+titleText" :visible.sync="addTitledialogVisible" width="50%" @close="addTitleDialogClose">
          <el-form :model="addTitleForm" :rules="addTitleRules" ref="addTitleRef" label-width="100px">
            <el-form-item :label="titleText" prop="attr_name">
              <el-input v-model="addTitleForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addTitledialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改参数对话框 -->
        <el-dialog :title="'修改'+titleText" :visible.sync="editTitledialogVisible" width="50%" @close="editTitleDialogClose">
          <el-form :model="editTitleForm" :rules="editTitleRules" ref="editTitleRef" label-width="100px">
            <el-form-item :label="titleText" prop="attr_name">
              <el-input v-model="editTitleForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editTitledialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
  data() {
    return {
      // 商品分类的数据列表
      cateList: [],
      // 级联选择框配置选项
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true,
        expandTrigger: 'hover'
      },
      // 选中项
      selectedCate: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      // 添加参数
      addTitledialogVisible: false,
      addTitleForm: {
        attr_name: ''
      },
      addTitleRules: {
        attr_name: [{
          required: true, message: '请输入参数名称', trigger: 'blur'
        }]
      },
      // 修改参数
      editTitledialogVisible: false,
      editTitleForm: {},
      editTitleRules: {
        attr_name: [{
          required: true, message: '请输入参数名称', trigger: 'blur'
        }]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
      // cateList赋值
      this.cateList = res.data
      // console.log(this.cateList)
      this.$message.success('获取参数列表成功')
    },
    // 监听级联选择框的变化的处理函数
    cateChange() {
      // console.log(this.selectedCate)
      this.getParamsData()
    },
    // 点击tab触发的事件
    handleTabClick() {
      // console.log(this.activeName)
      this.getParamsData()
    },
    // 获取参数信息
    async getParamsData() {
      if (this.selectedCate.length !== 3) {
        this.selectedCate = []
        this.manyTableData = []
        this.onlyTableData = []
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
      // 将动态参数分割成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      // console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 关闭添加属性对话框：清空数据
    addTitleDialogClose() {
      this.$refs.addTitleRef.resetFields()
    },
    // 添加属性或参数
    addParams() {
      this.$refs.addTitleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addTitleForm.attr_name,
          attr_sel: this.activeName
        })
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加参数成功')
        this.addTitledialogVisible = false
        this.getParamsData()
      })
    },
    // 关闭修改参数对话框：清空数据
    editTitleDialogClose() {
      this.$refs.editTitleRef.resetFields()
    },
    // 展示修改参数的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, { params: { attr_vals: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败')
      // console.log(res)
      this.editTitleForm = res.data
      this.editTitledialogVisible = true
    },
    // 提交修改参数
    editParams() {
      this.$refs.editTitleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editTitleForm.attr_id}`, {
          attr_name: this.editTitleForm.attr_name,
          attr_sel: this.activeName,
          attr_vals: this.editTitleForm.attr_vals
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改参数失败')
        this.$message.success('修改参数成功')
        this.editTitledialogVisible = false
        this.getParamsData()
      })
    },
    // 删除参数
    async deleteParams(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }
      this.$message.success('删除参数成功')
      this.getParamsData()
    },
    // 输入文本的函数
    handleInputConfirm(row) {
      // 判断输入值是否为空格
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
      }
      // 输入值不为空
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    // 保存修改的参数
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('修改参数失败')
      this.$message.success('修改参数成功')
    },
    // 点开按钮，展示文本输入框，传参是当前行的参数：scope.row
    showInput(row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick方法：当页面元素被重新渲染之后，才执行回调函数的代码，否则报错
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
  },
  computed: {
    // 若按钮被禁用，返回false，否则返回true
    isButtonDisabled() {
      if (this.selectedCate.length === 3) {
        return false
      }
      return true
    },
    cateId() {
      if (this.selectedCate.length === 3) {
        return this.selectedCate[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }

}
</script>
<style lang="scss" scoped>
.row{
    margin-top:18px;
    margin-bottom:18px;
}
.el-tag{
  margin:8px;
}
.input-new-tag{
  width: 120px;
}
</style>
